<template>
  <el-card>
    <div class="chat-app">
      <!-- 左侧好友列表 -->
      <div class="friend-list-container">
        <div>
          当前用户:
          <h3>{{ user.nickName }}</h3>
          <el-link class="logout-link" @click="logout">退出登录</el-link>
        </div>
        <br>
        <h3>好友列表</h3>
        <ul class="friend-list">
          <li v-for="friend in friendList" :key="friend.id">
            <el-link @click="changeChatFriend(friend.id)">
              {{ friend.nickName }}({{ friend.isOnline === 0 ? "在线" : "离线" }})
            </el-link>
          </li>
        </ul>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area-container">
        <!-- 上部聊天内容 -->
        <div class="chat-content">
          <!-- 动态类名，如果是当前用户发的消息，则靠右侧显示；反之靠左侧显示 -->
          <div class="chat-message" v-for="message in messages" :key="message.id"
               :class="{ 'sent': message.fromUser==user.id, 'received': message.fromUser!=user.id }">
            <p>{{ message.message }}</p>
          </div>
        </div>

        <!-- 下部输入框 -->
        <div class="input-box">
          <el-input placeholder="请输入消息..." v-model="newMessage"></el-input>
          <el-button @click.prevent="sendMessage">发送</el-button>
        </div>
      </div>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import {ref, reactive} from 'vue';
import router from "@/router/router.js";
import request from "@/utils/request.js";
import {ElMessage, ElNotification} from "element-plus";

// 当前用户信息
let user = ref({
  id: 0,
  username: '',
  password: '',
  nickName: ''
})

// 好友列表
let friendList = ref([])

// 过往消息
let messages = ref([])

// 正在输入的消息
let newMessage = ref('')

// 当前正在聊天的好友id
let nowFriendId = ref(0)

let socket = null;

/**
 * 退出登录
 */
const logout = () => {
  ElMessage.success("退出登陆成功")
  // 关闭websocket
  socket.close();
  // 删除用户信息
  localStorage.removeItem("user")
  // 前往登陆界面
  router.push('/login')
}

/**
 * 获取用户信息
 */
const getUser = () => {
  user.value = JSON.parse(localStorage.getItem("user"))
}

/**
 * 获取好友信息
 */
const getChatFriendsList = () => {
  request.get(`/friend_rel/list/${user.value.id}`).then((res) => {
    if (res.code === 200) {
      friendList.value = res.data
    } else {
      console.log('获取好友信息错误');
    }
  }).catch((err) => {
    console.log("err:", err);
  })
}

/**
 * 发送消息
 */
const sendMessage = () => {
  let message = {
    fromUser: user.value.id,
    toUser: nowFriendId.value,
    message: newMessage.value,
  }
  messages.value.push(message)
  socket.send(JSON.stringify(message))
  // 清除当前聊天框的信息
  newMessage.value = ''
}

/**
 * 获取与该用户的聊天记录
 */
const getMessages = (friendId) => {
  request.get(`/message/${user.value.id}/${friendId}`).then((res) => {
    if (res.code === 200) {
      messages.value = res.data
    } else {
      console.log('获取与该用户的聊天记录失败');
    }
  }).catch((err) => {
    console.log("err:", err);
  })
}

/**
 * 切换当前聊天好友
 */
const changeChatFriend = (id) => {
  // 获取与该用户的聊天记录
  getMessages(id)
  // 更新当前聊天的好友id
  nowFriendId.value = id
}

/**
 * socket初始化
 */
function init() {
  if (typeof WebSocket == 'undefined') {
    ElNotification({
      title: 'Error',
      message: `您的浏览器不支持websocket`,
      type: 'error',
    })
    return;
  }
  // 浏览器支持websocket
  let socketUrl = 'ws://localhost:10010/websocket/' + user.value.id;
  // 开启一个websocket服务
  socket = new WebSocket(socketUrl);
  // 打开事件
  socket.onopen = function () {
    console.log('websocket已经开启');
  }
  // 获得消息事件
  socket.onmessage = function (message) {
    try {
      let content = JSON.parse(message.data)
      messages.value.push(content)
      // 成功收到信息
      if (content.code === 200) {
        // 消息提示
        ElMessage.success(content.msg);
        let friend = friendList.value.filter(item => item.id == content.data)
            .map(item => item.isOnline=content.status);
        // friend[0].isOnline=friend[0].isOnline===1?0:1
        console.log("friend:", friend);
      }
      // console.log('messages:',messages);
      console.log('websocket收到数据:', content);
    } catch (e) {
      console.log("websocket收到数据解析失败:", e);
    }
  }
  // 关闭事件
  socket.onclose = function () {
    console.log('websocket已经关闭');
  }
  // 发生错误
  socket.onerror = function (err) {
    console.log('websocket发生错误:', err);
  }
}

// 获取用户信息
getUser()
// 获取好友信息
getChatFriendsList()
init()
</script>

<style scoped>
.chat-app {
  display: flex;
}

.friend-list-container {
  width: 25%;
  border-right: 1px solid #ccc;
}

.friend-list {
  list-style: none;
  padding: 0;
}

.friend-list li {
  padding: 10px;
  cursor: pointer;
}

.chat-area-container {
  width: 75%;
  height: 70vh;
}

.chat-content {
  /* 留出输入框的高度 */
  height: calc(100% - 90px);
}

.chat-message {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.chat-message.sent {
  text-align: right;
  margin-right: 10px;
  justify-content: flex-end;
}

.chat-message.received {
  text-align: left;
  margin-left: 10px;
}

.input-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 90px;
  border-top: 1px solid #ccc;
  background-color: #f5f5f5;
}

.logout-link {
  margin-left: 10px;
}
</style>